import json
import os
from urllib.parse import unquote
from flask import Blueprint, abort, jsonify,send_from_directory
from handle.logger import logger
from handle.S2Redis import sync_data_background,render_template,redis_client,socketio
from werkzeug.utils import secure_filename
# 创建一个蓝图对象
upload = Blueprint('upload', __name__)

@upload.route('/')
def index():
    return "你好"

@upload.route('/img/<filename>')
def upload_img(filename: str):
    filename = secure_filename(filename)

    if not filename.lower().endswith(('.jpg','.png')):
        abort(400, description="Only .jpg files are allowed.")

    # 服务器上的文件目录
    directory = os.path.join(os.getcwd(), 'upload/img/')

    # 检查文件是否存在
    if not os.path.exists(os.path.join(directory, filename)):
        abort(404, description="File not found.")

    return send_from_directory(directory, path=filename)


@upload.route('/img/sq/<path:filename>')
def upload_img_sq(filename: str):
    # 解码URL编码的文件名
    filename = unquote(filename)
    print(f"Decoded filename: {filename}")  # 调试用

    # 检查文件扩展名是否合法
    allowed_extensions = ('.jpg', '.png')
    if not any(filename.lower().endswith(ext) for ext in allowed_extensions):
        abort(400, description="Only .jpg and .png files are allowed.")

    # 文件存储的目录路径
    directory = os.path.join(os.getcwd(), 'upload/img/sq')

    # 检查文件是否存在
    file_path = os.path.join(directory, filename)
    print(f"Full file path: {file_path}")  # 调试用
    if not os.path.exists(file_path):
        abort(404, description="File not found.")

    # 返回文件
    return send_from_directory(directory, filename)